import React, {
  useState,
  useEffect,
  useCallback,
  Ref,
  useImperativeHandle,
  useMemo,
  useRef,
} from 'react';
import {
  Button,
  Table,
  Space,
  Modal,
  Form,
  message,
  Popconfirm,
  Empty,
  ConfigProvider,
} from 'antd';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import { InbizIcon, uuid, useEvents, deepClone, getApp, getPageString } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { useDebounceFunc } from '@inbiz/hooks';
import { GlobalRegistry } from '@inbiz/core';
import { observer } from '@formily/react';
import { getFormSystemMessage, schemaMap } from '@inbiz/render';
import { commonLang } from '@inbiz/utils'
// @ts-ignore
import Pagination from '@inbiz/basic/Pagination';
import { EditableRow, EditableCell } from './EditCell';
import ButtonsHeader from './ButtonsHeader';
import EditDrawer from './EditDrawer';
import EditModal from './EditModal';
import api from '../api';
import {
  getTableList as oldgetTableList,
  getvariateList,
  saveProcessManage,
  deleteProcessGroup,
  closeProcess,
  publishProcess,
  offProcess,
  saveVariate,
  getPageDetails,
  loadDetail,
  getProcessGroupList,
  getFormInfo,
  getLangComList,
} from '../servers';

type IRef = Ref<ReturnType<typeof api>>;

type DisableEditKeys = (
  | 'groupId'
  | 'mark'
  | 'name'
  | 'potentialStarterId'
  | 'pcPageKey'
  | 'pageKey'
  | 'sort'
  | 'descript'
)[];

export const processMessage = (res: string, key?: any) => {
  if (key) {
    return message.success({ content: res, key: 'inbizMessage' });
  }
  return message.error({ content: res, key: 'inbizMessage' });
};
interface IProps {
  activeGroupId: string;
  activeGroupInfo: any;
  rowData?: any[];
  listData?: any[];
  treeData: any[];
  $treeData: (info: any) => void;
  inline: string[];
  exposureConfig: {
    ownership: boolean;
  };
  pagesNum: number;
  processType?: boolean;
  defaultOption?: any[];
  processName?: boolean;
  toolbar: string[];
  listLoaded?: boolean;
  processGroup?: boolean;
  ScopeProcess: 'all' | 'app' | 'group';
  inbiz?: any;
  refs?: IRef;
  addGroup: any;
  refreshGroup: () => void;
  $activeGroupId: (id: string) => void;
  $activeGroupInfo: (info: any) => void;
  callBackEvents?: {
    onExtendsSave?: (params: any) => Promise<any>;
    formatTableData?: (rows: any[]) => any;
    onloadPcFilter?: (list: { name: string; value: string }[]) => { name: string; value: string }[]
    onloadH5Filter?: (list: { name: string; value: string }[]) => { name: string; value: string }[]
    setPcAutoRemark?: (info: { name: string; value: string }) => string
    setH5AutoRemark?: (info: { name: string; value: string }) => string
    ondeleteMessage?: (mess: string) => string;
    onParams?: (param: any) => any
    onRequest?: (fn: any) => any
    onData?: (data: any) => any
  };
  $rowData: any;
  emit?: {
    (type: 'onSave', handleType: 'add' | 'edit', data: object): void;
    (type: 'onSaveAndPublish', handleType: 'add' | 'edit', data: object): void;
    (type: 'onSelectGroup', groupId: string): void;
    (type: 'onDelete', groupId: string): void;
    (type: 'onAddModelOpen'): void;
    (type: 'onEditModelOpen', record: any): void;
  } | any;
  columnsConfig?: any;
}

const EditableContext = React.createContext<any>(null);
export { EditableContext };

// 表格按钮控制disabled的值
const btnValue = {
  edit: 1,
  designFlow: 1 << 1,
  setVariable: 1 << 2,
  releaseOrOff: 1 << 3,
  close: 1 << 4,
  delete: 1 << 5,
}

// 表格按钮控制算法
const getBtnValues = (val?: any) => {
  const arr = Object.values(btnValue);
  for (let i = arr?.length - 1; i >= 0; i--) {
    if (((val || 0) & arr[i]) !== arr[i]) {
      arr.splice(i, 1);
    }
  }
  return arr;
}

// 主体表格组件
const TableContent = (props: IProps) => {
  const {
    callBackEvents,
    emit,
    activeGroupId,
    activeGroupInfo,
    rowData,
    $rowData,
    listData,
    treeData,
    $treeData,
    refreshGroup,
    ScopeProcess,
    exposureConfig,
    inline = [],
    pagesNum,
    inbiz,
    processName,
    processType,
    listLoaded,
    refs,
    addGroup,
    $activeGroupId,
    $activeGroupInfo,
    processGroup,
    columnsConfig,
  } = props;

  const [form] = Form.useForm();
  // 主体表格数据
  const [dataList, $dataList] = useState<any[]>([]);
  // 添加/修改弹窗显示
  const [editModalVisible, $editModalVisible] = useState<boolean>(false);
  // 设置变量弹窗是否显示
  const [variateVisible, $variateVisible] = useState<boolean>(false);
  // 发布or下架弹窗
  const [publishOrOffVisiable, $publishOrOffVisiable] = useState<boolean>(false);
  // 设置变量表格数据
  const [variateList, $variateList] = useState<any[]>([]);
  // 编辑数据
  const [editData, $editData] = useState<any>(null);
  // 当前页数
  const [page, $page] = useState<number>(1);
  // 每页显示条数
  const [pageSize, $pageSize] = useState<number>(pagesNum);
  // 主体表格列表总数
  const [total, $total] = useState<number>();
  // 搜索文本
  const [searchText, $searchText] = useState<string>('');
  // 设置变量表格行id
  const [variateId, $variateId] = useState(null);
  //每行id
  const [rowId, $rowId] = useState<any>();
  // 每行key
  const [rowKey, $rowKey] = useState<any>();
  // 选择行id
  const [selectedRowKeys, $selectedRowKeys] = useState<any[]>([]);
  // 变量表格选择id
  const [variateSelectedRowKeys, $variateSelectedRowKeys] = useState<any[]>([]);
  // 当前删除的变量id数据
  const [delIds, $delIds] = useState<string[]>([]);
  // 列表加载
  const [loading, $loading] = useState(false);
  // pc控件
  const [pcControl, $pcControl] = useState<any[]>([]);
  // h5控件
  const [h5Control, $h5Control] = useState<any[]>([]);
  // 设置发起人DOM
  const [sponsor, setSponsor] = useState<any>(null);
  // 设计流程跳转参数
  const [edrmsparam, $edrmsparam] = useState<string>();
  // 头部Buttons组件传值
  const [headerDisabledValue, $headerDisabledValue] = useState();
  // 流程编辑表单禁止编辑项
  const [formEditKeys, $formEditKeys] = useState<DisableEditKeys>([]);
  // 编辑流程抽屉显示
  const [editProcessVisible, $editProcessVisible] = useState<boolean>(false)
  // 编辑抽屉修改后的数据
  const [editInfo, $editInfo] = useState<any>()
  // 新建/编辑流程保存loading
  const [saveLoading, $saveLoading] = useState<boolean>(false)
  // 新建流程保存并设计loading
  const [designLoading, $designLoading] = useState<boolean>(false)
  // 应用信息
  const appInfo = getApp()
  // 主体表格列
  const columns: any[] = useMemo(() => {
    return [
      {
        title: getMessage('ProcessManage.process_name'),
        dataIndex: 'name',
        width: 100,
        fixed: 'left',
        ellipsis: true,
        render: (txt: string) => {
          return <TextWidget>{txt}</TextWidget>;
        },
        onCell: (rec: any) => {
          return {
            title: getMessage(rec?.name)
          }
        }
      },
      {
        title: getMessage('ProcessManage.publishType'),
        dataIndex: 'actReProcdefIdRev',
        width: 100,
        render: (text: any) => {
          if (text === null) {
            return 0;
          } else {
            return text;
          }
        },
      },
      {
        title: getMessage('ProcessManage.process_type'),
        width: 100,
        dataIndex: 'mark',
        ellipsis: true,
        render: (txt: string) => {
          if (props.defaultOption?.length === 0) {
            return txt;
          } else {
            const text = props.defaultOption?.find((item) => item.key == txt);
            return <TextWidget>{text?.name || txt}</TextWidget>;
          }
        },
      },
      {
        title: getMessage('ProcessManage.process_group'),
        dataIndex: 'groupName',
        width: 100,
        ellipsis: true,
        render: (txt: string) => {
          return <TextWidget>{txt}</TextWidget>;
        },
        onCell: (rec: any) => {
          return {
            title: getMessage(rec?.groupName)
          }
        }
      },
      {
        title: getMessage('ProcessManage.createTime'),
        dataIndex: 'createTime',
        width: 100,
        render: (
          createTime: any,
        ) => moment(createTime).format('YYYY.MM.DD'),
      },
      {
        title: getMessage('ProcessManage.people_name'),
        dataIndex: 'potentialStartName',
        width: 100,
        ellipsis: true,
        render: (txt: any) => txt,
      },
      {
        title: getMessage('ProcessManage.process_state'),
        dataIndex: 'state',
        width: 100,
        render: (text: any) => {
          switch (text) {
            case 0:
              return <TextWidget>ProcessManage.state_unPublish</TextWidget>;
            case 1:
              return <TextWidget>ProcessManage.state_publish</TextWidget>;
            case 2:
              return <TextWidget>ProcessManage.state_off</TextWidget>;
            default:
              return <TextWidget>ProcessManage.state_close</TextWidget>;
          }
        },
      },
      {
        title: getMessage('ProcessManage.ownership'),
        width: 100,
        dataIndex: 'source',
        render: (text: any) => {
          switch (text) {
            case 0:
              return <TextWidget>ProcessManage.current</TextWidget>;
            default:
              return <TextWidget>ProcessManage.inherit</TextWidget>;
          }
        },
      },
      {
        title: getMessage('ProcessManage.operation'),
        dataIndex: 'operation',
        width: 345,
        fixed: 'right',
        render: (td: any, record: any) => (
          <Space
            size={[8, 1]}
            align="start"
            wrap
            onClick={(e: any) => {
              e.preventDefault();
              e.stopPropagation();
            }}
          >
            {inline.includes('compile') && (
              <Button disabled={getBtnValues(record.disabled).includes(btnValue.edit)} type='link' style={{ padding: 0 }} onClick={() => {
                props?.emit?.('onEditModelOpen', record)
                edit(record, () => $editProcessVisible(true));
              }}
              >
                <TextWidget>ProcessManage.edit</TextWidget>
              </Button>
            )}
            {inline.includes('designFlow') && (
              <Button disabled={getBtnValues(record.disabled).includes(btnValue.designFlow)} type='link' style={{ padding: 0 }} onClick={() => pageTurns(record)}>
                <TextWidget>ProcessManage.design</TextWidget>
              </Button>
            )}
            {inline.includes('setVariable') && (
              <Button disabled={getBtnValues(record.disabled).includes(btnValue.setVariable)} type='link' style={{ padding: 0 }}
                onClick={() => {
                  $variateVisible(true);
                  getVariateData(record);
                  $rowId(record.id);
                  $rowData(record);
                  if (record.formTypes == 2) {
                    getPageDetails({ processKey: record.key }).then(
                      (res: any) => {
                        if (res.details?.schema) {
                          let data = schemaMap(res.details.schema)
                          const selectOption = data.map((item) => {
                            return {
                              ...item,
                              name: getMessage(item.name),
                            } as { name: string; value: string }
                          });
                          const filSelectOption = callBackEvents?.onloadPcFilter?.(selectOption) || selectOption
                          $pcControl(filSelectOption)
                        } else {
                          $pcControl(callBackEvents?.onloadPcFilter?.([]) || [])
                        }
                      },
                    );
                    // @ts-ignore
                    getFormSystemMessage(false, { AppId: activeGroupInfo.appId }, GlobalRegistry.getDesignerLanguage(), record?.association?.split?.(',')?.[1])
                  } else {
                    $pcControl(callBackEvents?.onloadPcFilter?.([]) || [])
                  }
                }}
              >
                <TextWidget>ProcessManage.set_variate</TextWidget>
              </Button>
            )}
            {inline.includes('releaseOrOff') && (
              <Button disabled={getBtnValues(record.disabled).includes(btnValue.releaseOrOff)} type='link' style={{ padding: 0 }}
                onClick={() => {
                  $publishOrOffVisiable(true);
                  $rowId(record.id);
                  $rowKey(record.key);
                }}
              >
                <TextWidget>ProcessManage.publish_and_off</TextWidget>
              </Button>
            )}
            {inline.includes('closeOrdel') && (
              <Popconfirm
                title={getMessage('ProcessManage.comfirm_del')}
                onConfirm={() => del(record)}
                placement="topRight"
                disabled={record.state !== 3 || getBtnValues(record.disabled).includes(btnValue.delete)}
                okText={getMessage('ProcessManage.okText')}
                cancelText={getMessage('ProcessManage.cancelText')}
              >
                {
                  record.state == 3 ? <Button disabled={getBtnValues(record.disabled).includes(btnValue.delete)} type='link' style={{ padding: 0 }}><TextWidget>ProcessManage.del</TextWidget></Button>
                    :
                    <Button disabled={getBtnValues(record.disabled).includes(btnValue.close)} type='link' style={{ padding: 0 }} onClick={() => close(record)}><TextWidget>ProcessManage.close</TextWidget></Button>
                }
              </Popconfirm>
            )}
          </Space>
        ),
      },
    ];
  }, [GlobalRegistry.getDesignerLanguage(), activeGroupInfo])

  // columns列数据
  const [tableColumns, $tableColumns] = useState(columns)

  const formRef = useRef<any>();
  const isPreview: boolean = !location.hash?.startsWith?.('#/b/process-manage')

  const [configEvents] = useEvents(callBackEvents, emit);

  const getTableList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || oldgetTableList)(newParams as any)
    return await configEvents.current?.onData?.(data) || data
  }, []);

  useImperativeHandle(
    refs,
    () => ({
      ...api(
        configEvents,
        loadList,
        (info: { id: string, appId: string }) => {
          if (info?.appId && info?.id) {
            $activeGroupInfo(info)
            $activeGroupId(info.id)
          } else {
            message.error(getMessage('ProcessManage.setinfo_err'))
          }
        },
        $edrmsparam,
        $headerDisabledValue,
        $formEditKeys,
        (component: any) => {
          setSponsor(React.createElement(component));
        },
        (val: any) => {
          formRef.current?.setValue?.(val);
        },
      ),
    }),
    [],
  );

  const common = getMessage('ProcessManage.common');
  const strip = getMessage('ProcessManage.strip');

  // loadListData扩展方法
  const loadList = (e: {
    page: number;
    pageSize: number;
    searchText: string;
    groupId?: string;
  }) => {
    getTableData(e.page, e.pageSize, e.searchText, e.groupId);
  };

  // 设置变量表格列columnsVariate
  const defaultColumns: any[] = [
    {
      title: getMessage('ProcessManage.variate_name'),
      dataIndex: 'varName',
      editable: true,
      required: true,
      width: '22%',
      ellipsis: true,
      render: (txt: any, record: any) => {
        return <span title={txt}>{txt}</span>;
      },
    },
    {
      title: getMessage('ProcessManage.variate_type'),
      dataIndex: 'type',
      width: '22%',
      render: (text: any, record: any) => {
        if (text == 0) {
          return <TextWidget>ProcessManage.common_Type</TextWidget>;
        } else if (text == 1 && record.pcControl) {
          return <TextWidget>ProcessManage.control_type</TextWidget>;
        }
      },
      ellipsis: true,
    },
    {
      title: getMessage('ProcessManage.control'),
      dataIndex: 'pcControlId',
      editable: true,
      width: '22%',
      render: (txt: any, record: any) => {
        return <span title={record.pcControl}>{record.pcControl}</span>;
      },
      ellipsis: true,
    },
    // {
    //   title: getMessage('ProcessManage.move_Control'),
    //   dataIndex: 'moveControlId',
    //   editable: true,
    //   width: '20%',
    //   render: (txt: any, record: any) => {
    //     return <span title={record.moveControl}>{record.moveControl}</span>;
    //   },
    //   ellipsis: true,
    // },
    {
      title: getMessage('ProcessManage.describe'),
      dataIndex: 'remark',
      editable: true,
      width: '30%',
      render: (txt: any) => <span title={txt}>{txt}</span>,
      ellipsis: true,
    },
  ]; // 初始化页面时获取数据

  useEffect(() => {
    if (!activeGroupId || activeGroupId === '') {
      $dataList([]);
      $total(0);
      $searchText('');
      $page(1);
      resetSelect();
      $loading(false);
    } else {
      getTableData(1, pagesNum, '', activeGroupId);
      $page(1);
      $pageSize(pagesNum);
      $searchText('');
      resetSelect();
    }
  }, [activeGroupId, listLoaded, pagesNum]);

  //监听分页器
  useEffect(() => {
    $pageSize(pagesNum);
  }, [pagesNum]);

  // 档案：扩展代码隐藏列 + 兼容之前的列控制
  useEffect(() => {
    const tmpColumns = deepClone(columns)
    if (!exposureConfig?.ownership) {
      const index = tmpColumns.findIndex((item: any) => item.dataIndex === 'source');
      if (index > -1) {
        tmpColumns.splice(index, 1);
      }
    }
    if (processType === false) {
      const index = tmpColumns.findIndex((item: any) => item.dataIndex === 'mark');
      if (index > -1) {
        tmpColumns.splice(index, 1);
      }
    }
    if (processName === false) {
      const index = tmpColumns.findIndex((item: any) => item.dataIndex === 'groupName');
      if (index > -1) {
        tmpColumns.splice(index, 1);
      }
    }

    if (columnsConfig && Object.prototype.toString.call(columnsConfig) === '[object Object]') {
      for (let key in columnsConfig) {
        const index = tmpColumns.findIndex((item: any) => item.dataIndex == key);
        if (columnsConfig[key] === 'hide') {
          if (index > -1) {
            tmpColumns.splice(index, 1)
          }
        } else {
          tmpColumns.splice(columnsConfig[key]?.index ?? 1, 0, {
            dataIndex: key,
            title: getMessage(columnsConfig[key]?.title || '新增列'),
            width: columnsConfig[key]?.width || 100,
            render: columnsConfig[key]?.render
          })
        }
      }
    }

    $tableColumns(tmpColumns)
  }, [columnsConfig, processType, processName, exposureConfig?.ownership, edrmsparam, columns])

  //获取表格数据接口
  const getTableData = useDebounceFunc((
    page: number,
    pageSize: number,
    searchText: string,
    groupId?: string
  ) => {
    if (
      !processGroup &&
      (!activeGroupId || activeGroupId === '')
    ) {
      $dataList([]);
      $total(0);
      $searchText('');
      $page(1);
      resetSelect();
      $loading(false);
      return;
    } else {
      $loading(true);
      getTableList({
        groupId: groupId || activeGroupId,
        pageIndex: page,
        pageSize: pageSize,
        searchContext: searchText,
      }).then((res: any) => {
        $loading(false);
        if (res?.details) {
          const formatData = configEvents.current?.formatTableData;
          let data = res.details.rows;
          if (formatData) {
            data = formatData(res.details.rows);
          }
          $dataList(data);
          $total(res.details.total);
        } else {
          $dataList([]);
          $total(0);
        }
      });
    }
  });

  // 流程发布接口
  const publish = (key: any, data?: any, emit?: boolean) => {
    publishProcess({ key: key }).then((res: any) => {
      getTableData(page, pageSize, searchText);
      if (res.code == 200) {
        $publishOrOffVisiable(false);
        processMessage(getMessage('ProcessManage.publish_success'), true);
        $selectedRowKeys([]);
        emit &&
          props.emit?.('onSaveAndPublish', editData ? 'edit' : 'add', data);
      } else {
        $publishOrOffVisiable(false);
        processMessage(getMessage('ProcessManage.publish_error'));
      }
    });
  };

  //分页器多语言
  const [locale, $locale] = useState(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  useEffect(() => {
    $locale(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  }, [GlobalRegistry.getDesignerLanguage()]);

  // 编辑方法
  const edit = async (_record: any, fn: Function) => {
    const record = cloneDeep(_record);
    // 处理成员选择数据
    let names: string[] = record.potentialStartName.split(',');
    let types: string[] = record.potentialType.split(',');
    let ids: string[] = record.potentialStarterId.split(',');
    let arr: any[] = [];
    if (types?.length && ids?.length && names?.length) {
      for (let i = 0; i < types?.length; i++) {
        arr.push({
          key: `${types[i]}:${ids[i]}`,
          name: names[i],
        });
      }
    }
    record.potentialStarterId = arr;
    //  处理页面选择数据
    if (record.pageKey && record.pageKey !== '') {
      const [v1, v2, v3, v4, v5, v6] = record.pageKey.split(',');
      if ((v1 && v2 && v3 && v4) && (!v5 || !v6)) {
        try {
          let res = await loadDetail({ outId: v1, siteOutId: v3, appId: v4 });
          record.pageKey = `${record.pageKey},${res?.Route},${res?.Name}`;
        } catch { }
      }
    }
    if (record.pcPageKey && record.pcPageKey !== '') {
      const [v1, v2, v3, v4, v5, v6] = record.pcPageKey.split(',');
      if ((v1 && v2 && v3 && v4) && (!v5 || !v6)) {
        try {
          let res = await loadDetail({ outId: v1, siteOutId: v3, appId: v4 });
          record.pcPageKey = `${record.pcPageKey},${res?.Route},${res?.Name}`;
        } catch { }
      }
    }
    // 处理图标数据
    if (record.proLcon !== '') {
      if (record.proLcon?.trim().startsWith('v6_font_family')) {
        const [, v1, v2] = record.proLcon.split(' ');
        record.proLcon = {
          type: v1 || '',
          color: v2 || '',
        };
      } else {
        record.proLcon = {
          type: '',
        };
      }
    } else {
      record.proLcon = {
        type: '',
      };
    }
    if (record.formTypes == '2' && record?.association?.split?.(',')?.[1]) {
      const outid = record?.association?.split?.(',')?.[1]
      const info = await getFormInfo({ outId: outid, appId: activeGroupInfo?.appId })
      record.DataVersionId = info?.DataVersionId;
      record.Route = info?.Route;
    }
    $editData(record);
    fn?.();
  };

  // 编辑表单提交
  const submit = (formEdit: any, needPublish?: boolean, isDrawerEdit?: boolean, drawerFocus?: Function) => {
    formEdit?.validateFields?.().then((data: any) => {
      // 处理成员选择数据
      let ids: string[] = [],
        names: string[] = [],
        types: any[] = [],
        identityId: any[] = [];

      if (data.potentialStarterId && data.potentialStarterId?.length) {
        data.potentialStarterId.map((item: any) => {
          names.push(item.name);
          if (item.id?.indexOf(':') > -1) {
            let [v1, v2] = item.id?.split(':');
            ids.push(v2);
            types.push(v1);
            identityId.push(item.key?.split('-')[1]);
          } else {
            ids.push(item.id);
            types.push(item.memberarea);
            identityId.push(item.identityid);
          }
        });
      }

      if (ids?.length > 25) {
        processMessage(getMessage('ProcessManage.people_limit_number'));
        return;
      }

      // 处理流程图标
      let proLcon = data.proLcon;
      if (data.proLcon && data.proLcon !== '') {
        let { color, type } = data.proLcon;
        proLcon = `v6_font_family ${type || ''} ${color || ''}`.trim();
      }

      // 把表格data和当前行editData合并在一起
      let newEditData = {
        ...editData,
        ...data,
        potentialType: types.join(','),
        potentialStartName: names.join(','),
        potentialStarterId: ids.join(','),
        identityId: identityId.join(','),
        proLcon: proLcon,
      };

      const { mark, ...params } = newEditData;

      if (props.processType) {
        params.mark = mark;
      }

      if (!editData) {
        params.formKey = '';
        if (!params.groupId) {
          params.groupId = activeGroupId;
        }
      }

      if (params.sort == null) {
        processMessage(getMessage('ProcessManage.sort_message'));
        return;
      }

      // 处理关联表单或者表单分组的保存数据
      if (['1', '2'].includes(data.formTypes)) {
        params.association = data.formTypes == '1' ? data.selectFormGroup : data.selectForm
      }

      params.formTypes = Number(params.formTypes)
      params.appId = activeGroupInfo?.appId
      params.pcPageKey = params.pcPageKey?.trim?.() || ''
      params.pageKey = params.pageKey?.trim?.() || ''

      saveProcess(params, needPublish, data).then((res?: any) => {
        if (isDrawerEdit) {
          let type = 2, form = data.selectForm, asso = data.selectForm
          if (data.formTypes == '3') {
            type = 3
            form = ''
            asso = ''
          }
          if (data.formTypes == '1') {
            type = 2
            form = `${res?.Route},${res?.OutId},${res.Name}`
            asso = `${res?.Route},${res?.OutId},${res.Name}`
            formEdit?.setFieldsValue?.({
              formTypes: String(type),
              selectForm: form
            });
          }
          $editInfo({
            ...editData,
            formTypes: type,
            selectForm: form,
            association: asso,
            DataVersionId: res?.DataVersionId
          })
          // 编辑保存不关闭弹窗
          // $editProcessVisible(false)
        }
      })
    }).catch(() => {
      drawerFocus?.()
    })
  };

  // 表单数据保存接口
  const saveProcess = async (data: any, needPublish?: boolean, formData?: any) => {
    if (needPublish) {
      $designLoading(true)
    } else {
      $saveLoading(true)
    }
    const saveRequest = editData
      ? saveProcessManage
      : configEvents.current?.onExtendsSave || saveProcessManage;
    const res: any = await saveRequest(data)
    return new Promise((resolve, reject) => {
      if (res.code == 200) {
        props.emit?.('onSave', editData ? 'edit' : 'add', data)
        !needPublish &&
          processMessage(getMessage('ProcessManage.save_success'), true)
        $editModalVisible(false)
        getTableData(page, pageSize, searchText, res.activeGroupId)
        if (needPublish) {
          /* 6.5.3及之前的发布流程-调发布接口-废弃*/
          // publish(data.key, data, true);
          // 去设计
          // TODO...Jump...
          toDesign({
            id: editData ? data?.id : res?.details?.processId, // 编辑去当前数据，新建时取新建返回的数据
            type: data?.formTypes,
            outId: data?.formTypes != '1' ? data?.selectForm?.split(',')?.[1] || '' : res?.details?.OutId, // 新建时取新建返回的数据
            route: data?.formTypes != '1' ? data?.selectForm?.split(',')?.[0] || '' : res?.details?.Route, // 新建时取新建返回的数据
            groupId: data?.groupId
          }, formData.formTypes == '2')
        }
        resolve(res?.details)
      } else if (res.details == -4) {
        processMessage(getMessage('ProcessManage.save_process_name_error'))
        reject()
      } else if (res.details == -7) {
        processMessage(getMessage('ProcessManage.save_mark_error'))
        reject()
      } else {
        processMessage(getMessage('ProcessManage.save_error'))
        reject()
      }
      $designLoading(false)
      $saveLoading(false)
    })
  };

  // 根据appId查应用路由
  const findDomain = (id: string) => {
    if (ScopeProcess != 'app') {
      return treeData?.find?.((i: any) => i.Id == id)?.Domain
    }
    return appInfo?.App?.Domain
  }

  // 根据分组id查appid
  const findAppid = (id: string) => {
    if (ScopeProcess != 'app') {
      return treeData?.find?.((i: any) => i.Children?.find((j: any) => j.id == id))?.Children?.find?.((j: any) => j.id == id)
    } else {
      return listData?.find?.((i: any) => i.id == id)?.appId
    }
  }

  // 去设计
  const toDesign = (rec: any, designProcess?: boolean) => {
    const active = designProcess ? '2' : '1'
    let url = ''
    const appid = (!rec.groupId || rec.groupId == activeGroupInfo?.id) ? activeGroupInfo?.appId : findAppid(rec.groupId)
    const domain = findDomain(appid) || appInfo?.App?.Domain
    if (process.env.NODE_ENV == 'development') {
      url = `${location.origin}/${domain}?iswf=true${rec.outId ? '&active=' + active : ''}${rec.outId ? '&formid=' + rec.outId : ''}&processid=${rec.id}${edrmsparam ? '&edrmsparam=' + edrmsparam : ''}#/editor${rec.route ? '/' + rec.route : ''}`
    } else {
      url = `${location.origin}/inbiz/web/editor/${domain}?iswf=true${rec.outId ? '&active=' + active : ''}${rec.outId ? '&formid=' + rec.outId : ''}&processid=${rec.id}${edrmsparam ? '&edrmsparam=' + edrmsparam : ''}#/${rec.route ? rec.route : ''}`
    }
    window.open(url)
  }

  // 搜索数据
  const filterData = (text: any) => {
    $searchText(text);
    getTableData(1, pageSize, text);
    $page(1);
    resetSelect();
  };

  // 获取设置变量表格数据接口
  const getVariateData = (record: any) => {
    getvariateList({
      processDefinitionId: record.actReProcdefId,
      processId: record.id,
      pageSize: 9999,
    }).then((res: any) => {
      $variateList(res?.details?.rows || []);
    });
  };

  // 删除接口
  const del = (record: any) => {
    deleteProcessGroup({ processId: record.id }).then((res: any) => {
      props.emit?.('onDelete', res)
      if (res.code == 200) {
        processMessage(getMessage('ProcessManage.del_success'), true);
        getTableData(page, pageSize, searchText);
        $selectedRowKeys([]);
      } else {
        const mess = configEvents.current?.ondeleteMessage?.(res.message) || res.message
        processMessage(mess)
      }
    });
  };

  // 关闭接口
  const close = (record: any) => {
    closeProcess({ key: record.key }).then((res: any) => {
      if (res.code == 200) {
        processMessage(getMessage('ProcessManage.close_success'), true);
        getTableData(page, pageSize, searchText);
        $selectedRowKeys([]);
      } else {
        processMessage(getMessage('ProcessManage.close_error'));
      }
    });
  };

  // 设计流程跳转
  const pageTurns = (record: any) => {
    toDesign({
      id: record?.id,
      type: record?.formTypes,
      outId: record?.formTypes == '2' ? record?.association?.split(',')?.[1] : '',
      route: record?.formTypes == '2' ? record?.association?.split(',')?.[0] : '',
    }, true)
    /* 老版本调整逻辑-6.5.3后废弃 */
    // const id = record?.id
    // let lang = GlobalRegistry.getDesignerLanguage();
    // if (lang === 'en-us') {
    //   lang = 'en'
    // } else if (lang === 'ja') {
    //   lang = 'ja'
    // } else {
    //   lang = 'zh-cn'
    // }
    // let origin = location.origin;
    // let pathname = '/edoc2Flow-web/v5-processManager/show';
    // let search = edrmsparam
    //   ? `?id=${id}&edrmsparam=${edrmsparam}`
    //   : `?id=${id}`;
    // let token = `&orgToken=${Cookies.get('token')}`;
    // let fixed = `&loginName=&lng=${lang}&skin=`;
    // let url = `${origin}${pathname}${search}${token}${fixed}`;
    // window.open(url);
  };

  // 增加设置变量表格行
  const addVariateRow = () => {
    $variateList([
      ...variateList,
      {
        id: uuid(20, 60),
        varName: '',
        type: '0',
        pcControl: '',
        pcControlId: '',
        moveControlId: '',
        moveControl: '',
        remark: '',
      },
    ]);
  };

  // 删除设置表单表格行
  const delVariate = () => {
    if (variateSelectedRowKeys?.length === 0) {
      processMessage(getMessage('ProcessManage.select_del'));
    } else {
      $variateList(
        variateList.filter(
          (item: any) => !variateSelectedRowKeys.includes(item.id),
        ),
      );
      $delIds([...delIds, ...variateSelectedRowKeys]);
      $variateSelectedRowKeys([]);
    }
  };

  const handleSave = (row: any) => {
    const newData = [...variateList];
    const index = newData.findIndex((item) => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    $variateList(newData);
  };

  // 恢复选中rowData数据
  const resetSeleData = () => {
    $rowData(dataList?.filter?.((i: any) => selectedRowKeys?.includes?.(i?.id)) || [])
  }

  //设置变量表格保存
  const save = () => {
    let list: any[] = [...variateList];
    let varNames: string[] = [];
    for (let i = 0; i < list?.length; i++) {
      for (let j = 0; j < defaultColumns?.length; j++) {
        if (defaultColumns[j].required) {
          let key = defaultColumns[j].dataIndex;
          if (!list[i][key] || list[i][key] === '') {
            let dom = document.getElementById(`cell-${key}-${list[i].id}`);
            dom?.click();
            setTimeout(() => {
              form.validateFields();
            }, 0);
            return;
          }
        }
      }
      if (varNames.includes(list[i].varName)) {
        processMessage(getMessage('ProcessManage.setVariate_name_same'));
        return;
      }
      if (list[i].varName?.length > 32) {
        message.info(getMessage(`ProcessManage.lineVariableTooLong`, { 0: i + 1 }))
        return;
      }
      varNames.push(list[i].varName);
    }
    // @ts-ignore
    const dels: string[] = [...new Set(delIds)];
    variateSelectedRowKeys;
    let data1 = {
      ids: dels.join(','),
      processId: rowId,
      vars: JSON.stringify(list),
    };

    saveVariate(data1).then((res: any) => {
      if (res.code == 200) {
        getVariateData(rowData);
        processMessage(getMessage('ProcessManage.save_success'), true);
        $variateVisible(false);
        resetSeleData()
      } else {
        message.error(res?.message);
      }
    });
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columnsVariate = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        required: col.required,
        pcControl: pcControl,
        h5Control: h5Control,
        variateId: variateId,
        setNowKey: (e: any) => $variateId(e),
        handleSave,
        callBackEvents,
      }),
    };
  });

  // 每次复选框发生变化时调用
  const onSelectChange = (newSelectedRowKeys: any, record: any) => {
    $selectedRowKeys(newSelectedRowKeys);
    $rowData(record);
    $rowKey(record[0]?.key);
  };

  const rowSelection = {
    selectedRowKeys,
    columnWidth: '40px',
    onChange: onSelectChange,
  };

  const onSelectChange1 = (newSelectedRowKeys: any) => {
    $variateSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection1 = {
    selectedRowKeys: variateSelectedRowKeys,
    onChange: onSelectChange1,
  };

  // 清空选中
  const resetSelect = () => {
    $selectedRowKeys([]);
    $rowData([]);
    $rowId('');
    $rowKey('');
  };

  // 点当前行任意地方可选中
  const onSelectRow = (record: any) => {
    let idx: any = rowData?.findIndex((item: any) => item.id === record.id);
    if (idx > -1) {
      let newData = rowData?.filter((item: any) => item.id !== record.id);
      $rowData(newData);
    } else {
      $rowData([...(rowData || []), record]);
    }

    $rowId(record.id);
    const selectedList = [...selectedRowKeys];
    if (selectedList.indexOf(record.id) >= 0) {
      //当点击选中的数据，取消选中
      selectedList.splice(selectedList.indexOf(record.id), 1);
    } else {
      //选中的数据放入数组
      selectedList.push(record.id);
    }
    $selectedRowKeys(selectedList);
    $rowKey(record.key);
  };

  // 头部按钮-刷新
  const btnRefresh = (groupId: string) => {
    if (!searchText && !groupId) {
      return
    }
    getTableData(page, pageSize, searchText, groupId);
    resetSelect();
  };

  // 头部按钮-新建
  const btnAdd = () => {
    props?.emit?.('onAddModelOpen')
    $editModalVisible(true);
    $editData(null);
  };

  // 异步加载树节点的子节点(获取指定应用下分组列表)
  const onLoadData = async (key?: string) => {
    if (ScopeProcess == 'all') {
      const nowGroup: any = await getProcessGroupList({ pageSize: 9999, appId: key })
      const tree = treeData.map((i: any) => {
        if (i.id == key) {
          if (Array.isArray(nowGroup?.details?.rows) && nowGroup.details.rows.length) {
            return { ...i, Children: nowGroup.details.rows }
          } else {
            return { ...i, Children: [] }
          }
        }
        return i
      })
      $treeData(tree)
    } else {
      refreshGroup()
    }
  }

  return (
    <div className="right-content-box">
      {/* 头部按钮组 */}
      <ButtonsHeader
        toolbar={props.toolbar}
        selectKey={selectedRowKeys}
        refresh={btnRefresh}
        add={btnAdd}
        filter={filterData}
        listData={listData}
        rowData={rowData}
        inbizInfo={inbiz}
        activeGroupId={activeGroupId}
        activeGroupInfo={activeGroupInfo}
        $activeGroupId={$activeGroupId}
        $activeGroupInfo={$activeGroupInfo}
        ScopeProcess={ScopeProcess}
        treeData={treeData}
        publish={publish}
        rowKey={rowKey}
        refreshGroup={onLoadData}
        dataList={dataList}
        processMessage={processMessage}
        getTableData={getTableData}
        disabledValue={headerDisabledValue}
      />
      <div className="table-list">
        <Table
          rowKey="id"
          bordered
          size="middle"
          className={isPreview ? '' : 'b-process-manage-table'}
          rowSelection={rowSelection}
          rowClassName="tableList"
          columns={tableColumns}
          dataSource={dataList}
          pagination={false}
          scroll={{ x: 1000 }}
          loading={loading}
          onRow={(record) => ({
            onClick: () => onSelectRow(record),
          })}
          locale={{
            emptyText: (
              <Empty
                image={loading ? null : Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  loading ? null : (
                    <TextWidget>ProcessManage.no_data</TextWidget>
                  )
                }
              />
            ),
          }}
        />
        {/* 分页 */}
        <ConfigProvider locale={locale}>
          <Pagination
            refreshData={() => {
              btnRefresh(activeGroupId);
            }}
            pageRefresh={true}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: [10, 20, 30, 50, 100],
              showLessItems: true,
              // @ts-ignore
              showTotal: true,
            }}
            onPageChange={({ current, pageSize }) => {
              getTableData(current, pageSize, searchText);
              $page(current);
              $pageSize(pageSize);
            }}
          />
        </ConfigProvider>
        {/* 添加弹窗 */}
        <Modal
          visible={editModalVisible}
          className="process-manage-add-modal-box"
          title={
            editData
              ? getMessage('ProcessManage.edit_process')
              : getMessage('ProcessManage.add_process')
          }
          width={700}
          onCancel={() => $editModalVisible(false)}
          footer={false}
          destroyOnClose
          maskClosable={false}
        >
          {/* 添加流程弹窗主体 */}
          <EditModal
            className="main-body"
            $editModalVisible={$editModalVisible}
            editData={editData}
            appId={getApp()?.AppId}
            submit={submit}
            publish={publish}
            rowId={rowId}
            $editData={$editData}
            processMessage={processMessage}
            width="600px"
            designLoading={designLoading}
            saveLoading={saveLoading}
            sponsor={sponsor}
            editRefs={formRef}
            disableKeys={formEditKeys}
            {...props}
          />
        </Modal>
        {/* 修改抽屉 */}
        <EditDrawer
          visible={editProcessVisible}
          $visible={$editProcessVisible}
          record={editData}
          processName={props.processName}
          processType={props.processType}
          defaultOption={props.defaultOption}
          emit={emit}
          submit={submit}
          saveProcess={saveProcess}
          design={toDesign}
          editInfo={editInfo}
          saveLoading={saveLoading}
          $editInfo={$editInfo}
          activeGroupInfo={activeGroupInfo}
          findDomain={findDomain}
          editProps={{
            sponsor,
            editRefs: formRef,
            disableKeys: formEditKeys,
            listData: props.listData,
            addGroup: addGroup,
            activeGroupInfo: activeGroupInfo,
            submit,
            $editModalVisible,
          }}
        />
        {/* 设置变量弹窗 */}
        <Modal
          visible={variateVisible}
          className="variate-modal-content"
          title={getMessage('ProcessManage.set_variate')}
          width={700}
          maskClosable={false}
          onCancel={() => {
            $variateVisible(false);
            $variateId(null);
            $variateList([]);
            $delIds([]);
            $variateSelectedRowKeys([]);
            resetSeleData()
          }}
          onOk={() => {
            save();
            $variateSelectedRowKeys([]);
          }}
          cancelText={getMessage('ProcessManage.cancelText')}
          okText={getMessage('ProcessManage.okText')}
        >
          <div className="main-body">
            <Space size="middle" align="start">
              <Button
                type="primary"
                onClick={() => {
                  addVariateRow();
                }}
              >
                <TextWidget>ProcessManage.addText</TextWidget>
              </Button>
              <Button
                danger
                onClick={() => {
                  delVariate();
                }}
              >
                <TextWidget>ProcessManage.delText</TextWidget>
              </Button>
            </Space>
            <Form form={form}>
              <EditableContext.Provider value={form}>
                <Table
                  rowSelection={rowSelection1}
                  components={components}
                  size="middle"
                  bordered
                  rowKey="id"
                  columns={columnsVariate}
                  dataSource={variateList}
                  scroll={{ y: 287 }}
                  rowClassName={'variate-selete-edit-able'}
                  pagination={false}
                  onRow={(record, index: any) => {
                    return {
                      onClick: () => {
                        $variateId(record.id);
                        // setIindex(index + 1)
                      },
                    };
                  }}
                />
              </EditableContext.Provider>
            </Form>
          </div>
        </Modal>
        {/* 发布&下架弹窗 */}
        <Modal
          title={getMessage('ProcessManage.publish_and_off')}
          visible={publishOrOffVisiable}
          maskClosable={false}
          className="publish-off-modal"
          onCancel={() => $publishOrOffVisiable(false)}
          footer={null}
        >
          <div
            className="common publish"
            onClick={() => {
              publish(rowKey);
            }}
          >
            <span className="common-text">
              <div>{getMessage('ProcessManage.publish_title')}</div>
              <div className="describe">
                {getMessage('ProcessManage.publish_describ')}
              </div>
            </span>
            <span className="publishIcon">
              <InbizIcon type="icon-ic-waifa" />
            </span>
          </div>
          <div
            className="common off"
            onClick={() => {
              offProcess({ key: rowKey }).then((res: any) => {
                if (res.code == 200) {
                  getTableData(page, pageSize, searchText);
                  $publishOrOffVisiable(false);
                  processMessage(
                    getMessage('ProcessManage.off_success'),
                    true,
                  );
                }
              });
            }}
          >
            <div className="common-text">
              <div>{getMessage('ProcessManage.off_title')}</div>
              <div className="describe">
                {getMessage('ProcessManage.off_describ')}
              </div>
            </div>
            <div className="offIcon">
              <InbizIcon type="icon-ic-xiajia" />
            </div>
          </div>
        </Modal>
      </div>
    </div>
  );
};

export default observer(TableContent);
